import tornado.web
from tornado.options import options
import datetime
from PyWebsite3.common import float_2_percentage, df_float_formated
import MutualFundScore.load_data as load_data
import json
import pandas as pd


class SearchHandler(tornado.web.RequestHandler):
    # 在数据库中完成搜索数据
    def get(self):
        # 输入参数
        keyword = self.get_arguments("keyword", strip=True)
        instrument_type = self.get_arguments("instrument_type", strip=True)

        result_document_list = []

        if len(keyword) != 0 and len(instrument_type) != 0 and keyword[0] != "":
            keyword = keyword[0]
            instrument_type = instrument_type[0]
            #
            database = options.database
            datetime_update = datetime.datetime.now()

            instrument_type_list = ["stock", "mutualfund", "index", "future"]
            if instrument_type != "unknown":
                instrument_type_list = [instrument_type]

            for instrument_type in instrument_type_list:
                table_name = "instrument_" + instrument_type
                results1 = database.ExecuteSQL("financial_data", "select symbol, description from financial_data." + table_name + " where symbol like '%" + keyword + "%'")
                results2 = database.ExecuteSQL("financial_data", "select symbol, description from financial_data." + table_name + " where description like '%" + keyword + "%'")
                results = results1 + results2
                for element in results:
                    document = {}
                    document["symbol"] = element[0]
                    document["description"] = element[1]
                    document["instrument_type"] = instrument_type
                    result_document_list.append(document)

        self.render("search.html",
                    result_document_list=result_document_list)

    def post(self):
        a = 0
        pass